import request from "@/utils/request";
import downloadUtil from "@/utils/download-util";
export default {
  data() {
    return {
      // 分页数据
      pager: { page: 1, limit: 10, totalCount: 0 },
      // 表格
      tableData: [],
      // 查询表单数据
      searchData: {},
      // 选中行
      tableSelectRows: [],
      // 弹窗标题
      titleMap: { add: "添加", update: "修改", view: "详情" },
      // 添加/修改模式（add/update）
      dialogType: "",
      // 弹窗显示隐藏
      dialogFormVisible: false,
      // 表单临时数据
      temp: {},
      isLoading: false,
      dialogIndex: 0,
      // 用于绑定时间选择框 不提交
      timePickageValue: "",
      // 文件列表
      fileList: [],
    };
  },
  methods: {
    // 查询按钮
    searchBtnHandle() {
      this.pager.page = 1;
      this.loadTableList();
    },
    // 显示全部
    resetTableList() {
      this.pager.page = 1;
      this.searchData = {};
      this.timePickageValue = "";
      this.loadTableList();
    },
    // 加载表格
    loadTableList() {
      this.isLoading = true;
      const params = { ...this.pager, params: JSON.stringify(this.searchData) };
      request({
        url: this.url.list,
        method: "get",
        params,
      }).then((response) => {
        const { data } = response;
        this.pager.totalCount = data.total;
        this.tableData = data.records;
        this.isLoading = false;
      });
    },
    // 监听选中行
    handleTableSelectChange(rows) {
      this.tableSelectRows = rows;
    },
    // 监听分页
    handleCurrentChange(page) {
      this.pager.page = page;
      this.loadTableList();
    },
    // 分页条数改变
    handleSizeChange(size) {
      this.pager.limit = size;
      this.loadTableList();
    },
    // 清空表单temp数据
    resetTemp() {
      this.temp = { orderIndex: 0 };
      if (this.fileList) {
        this.fileList = [];
      }
      this.dialogIndex++;
    },
    // 打开添加窗口
    openAdd() {
      this.resetTemp();
      this.dialogFormVisible = true;
      this.dialogType = "add";
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });

      // 判断打开弹窗是否需要获取列表数据
      this.needGetParam && this.getSelectData();
    },
    // 获取详情数据打开弹窗 传递数据异步传递数据使用
    getRowData(row, type) {
      return new Promise((reslove, reject) => {
        var that = this;
        request({
          url: this.url.info,
          method: "get",
          params: {
            [this.idName ? this.idName : "id"]:
              row[this.idName ? this.idName : "id"],
          },
        })
          .then((response) => {
            const { data } = response;
            that.temp = Object.assign({}, data);
            that.dialogType = type;
            that.dialogFormVisible = true;
            if (that.temp.fileInfo) {
              that.fileList = JSON.parse(that.temp.fileInfo);
            }
            reslove(data);
            that.$nextTick(() => {
              that.$refs["dataForm"].clearValidate();
            });
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 打开修改窗口
    openUpdate(row) {
      this.needGetParam && this.getSelectData();
      if (row) {
        this.$refs.dataTable.clearSelection();
        this.$refs.dataTable.toggleRowSelection(row, true);
      }
      if (this.tableSelectRows.length <= 0) {
        this.$message({ message: "请选择一条数据修改！", type: "warning" });
      } else if (this.tableSelectRows.length > 1) {
        this.$message({
          message: "修改时，只允许选择一条数据！",
          type: "warning",
        });
      } else {
        // 修改弹窗
        var that = this;
        request({
          url: this.url.info,
          method: "get",
          params: {
            [this.idName ? this.idName : "id"]:
              row[this.idName ? this.idName : "id"],
          },
        }).then((response) => {
          const { data } = response;
          that.temp = Object.assign({}, data);
          that.dialogType = "update";
          that.dialogFormVisible = true;
          that.$nextTick(() => {
            that.$refs["dataForm"].clearValidate();
          });
        });
      }
    },
    // 打开查看窗口
    async openView(row) {
      this.needGetParam && this.getSelectData();

      var that = this;
      request({
        url: this.url.info,
        method: "get",
        params: {
          [this.idName ? this.idName : "id"]:
            row[this.idName ? this.idName : "id"],
        },
      }).then((response) => {
        const { data } = response;
        that.temp = Object.assign({}, data);
        that.dialogType = "view";
        that.dialogFormVisible = true;
        if (that.temp.fileInfo) {
          that.fileList = JSON.parse(that.temp.fileInfo);
        }
        that.$nextTick(() => {
          that.$refs["dataForm"] && that.$refs["dataForm"].clearValidate();
        });
      });
    },
    // 添加/修改，保存事件
    saveData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          let data = { ...this.temp };
          if (this.dialogType === "update") {
            request({
              url: this.url.update,
              method: "post",
              data,
            }).then((response) => {
              this.$message({ type: "success", message: "修改成功！" });
              this.loadTableList();
              this.dialogFormVisible = false;
            });
          } else {
            request({
              url: this.url.add,
              method: "post",
              data,
            }).then((response) => {
              this.$message({ type: "success", message: "添加成功！" });
              this.loadTableList();
              this.dialogFormVisible = false;
            });
          }
        }
      });
    },
    // 删除
    deleteByIds(row) {
      if (row) {
        this.$refs.dataTable.clearSelection();
        this.$refs.dataTable.toggleRowSelection(row, true);
      }
      if (this.tableSelectRows.length <= 0) {
        this.$message({ message: "请选择一条数据删除！", type: "warning" });
      } else {
        this.$confirm("确定要删除吗?", "删除提醒", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 执行删除
          const data = this.tableSelectRows.map(
            (r) => r[this.idName ? this.idName : "id"]
          );
          request({
            url: this.url.delete,
            method: "post",
            data,
          }).then((response) => {
            this.$message({ type: "success", message: "删除成功！" });
            this.loadTableList();
          });
        });
      }
    },
    // 导出Excel文件
    exportExcel() {
      const params = { params: JSON.stringify(this.searchData) };
      downloadUtil.download(this.url.export, params, this.exportName);
    },
    // 导入Excel成功，提示
    importExcelSuccess(response) {
      if (response.code === "200") {
        this.$message({ type: "success", message: "导入成功！" });
        this.loadTableList();
      } else {
        this.$message({ type: "error", message: response.message });
      }
    },
    // 设置时间
    setSearchDate(val) {
      this.searchData.startTime = val[0];
      this.searchData.endTime = val[1];
    },
    openFile(file) {
      downloadUtil.downLoadFile(file.url, file.name);
    },
  },
};
